package com.os.opencv.java.chapter8;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

public class MatchTemplate {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("/Users/matt/Pictures/gdl.jpg");
        HighGui.imshow("fish", src);
        HighGui.waitKey(0);

        //读取图像模板并在屏幕上显示
        Mat template = Imgcodecs.imread("/Users/matt/Pictures/gdl-1.jpg");
        HighGui.imshow("template", template);
        HighGui.waitKey(0);

        //进行模板匹配，结果在result中
        Mat result = new Mat();
        Imgproc.matchTemplate(src, template, result, Imgproc.TM_CCOEFF);

        //去除最大值的位置TM_CCOEFF模式用最大值
        Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
        Point pt = mmr.maxLoc;

        //用矩阵画出匹配位置并在屏幕上显示
        Scalar red = new Scalar(0,0,255);
        Imgproc.rectangle(src, pt, new Point(pt.x + template.cols(), pt.y + template.rows()), red, 3);
        HighGui.imshow("match", src);
        HighGui.waitKey(0);
        System.exit(0);
    }
}
